import { Login, Logout } from '../../services/account/index';
import { setLocalStorage, clearLocalStorage } from '../../utils/cookieHelper';
import { message } from 'antd';
import { routerRedux } from 'dva/router';


export default {

  namespace: 'account',

  state: {
    loading: false,
    errorMsg: '',
    formstate: 'success',
    fromurl: '/'
  },

  subscriptions: {
    setup({ history, dispatch }) {
      // 监听 history 变化，当进入 `/` 时触发 `load` action
      return history.listen(({ pathname, query }) => {
        if (pathname == "/login") {
          dispatch({
            type: 'esetfromurl',
            payload: query.from === undefined ? '/' : query.from
          });
        }
      });
    },
  },

  effects: {
    * go({ payload }, { call, put }) {
      yield put(routerRedux.push(payload.url));
    },
    * login({ payload }, { call, put }) {
      yield put({ type: 'showloading' });
      const result = yield call(Login, payload.formData);
      yield put({ type: 'hideloading' });
      const { data } = result;
      if (data.success) {
        message.success(data.message);
        const d = data.data;
        // 存入页面缓存
        setLocalStorage('power', d.menus);
        //跳转到指定页面
        window.location.href = payload.fromUrl;
      } else {
        const msg = data.message === undefined ? '服务器发生错误.' : data.message;
        yield put({ type: 'setmessage', payload: { msg } })
        message.error(data.message);
      }
    },
    * logout({ payload: guid }, { call, put }) {
      yield put({ type: 'showloading' });
      const result = yield call(Logout);
      yield put({ type: 'hideloading' });
      const { data } = result;
      if (data.success) {
        message.success(data.message);
        // 清除
        clearLocalStorage('power');
        // 为了看起来不闪屏，延迟0.5秒后跳转
        setTimeout(() => {
          window.location.href = '/login';
        }, 500);
      } else {
        message.error(data.message);
      }
    },
    * esetfromurl({ payload }, { call, put }) {
      yield put({ type: 'setfromurl', payload: payload })
    }
  },
  reducers: {
    showloading(state) {
      return {...state, loading: true };
    },
    hideloading(state) {
      return {...state, loading: false };
    },
    setmessage(state, { payload }) {
      return {...state, errorMsg: payload.msg, formstate: 'error' };
    },
    setfromurl(state, { payload }) {
      return {...state, fromurl: payload };
    }
  },

};